import socket
import time
import threading

s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)  

s.bind(('0.0.0.0', 9999))                           

s.listen(1)                                            

print('Server is running...')
                               
def TCP(sock, addr):
    with open('/home/test.log', 'a') as myfile:
        myfile.write('new connection %s:%s\n' %addr)                                   
    print('Accept new connection from %s:%s.' %addr)   
    while True:
        data = sock.recv(1024)                         
        time.sleep(1)                                  
        if not data or data.decode() == 'quit':        
            break
        sock.send(data.decode('utf-8').upper().encode())
        result = data.decode('utf-8').upper().encode()
        with open('/home/test.log', 'a') as myfile:
            myfile.write('result: %s\n' %result)

    sock.close()                                      
    print('Connection from %s:%s closed.' %addr)
    with open('/home/test.log', 'a') as myfile:
        myfile.write('Connection from %s:%s closed.\n' %addr)
        myfile.write('------\n')

while True:

    sock, addr = s.accept()                            
    TCP(sock, addr)
